import os
import json

from flask import Blueprint, request
from flask import render_template, request
from flask_login import login_required, current_user

from sqlalchemy.sql.expression import true

from applications.extensions import db
from applications.models.version_model import Version
from applications.common.utils.base_response import exception_response, ErrorCodes, success_response
from .utils import check_project

version_manger = Blueprint('version', __name__, url_prefix='/api/version')


@version_manger.route("/select_version")
@login_required
def select_version():
    return render_template("version_server/index.html")


# 版本管理
@version_manger.get('/versions/')
def version_list():
    page = request.args.get('page', 1)
    page_size = request.args.get('page_size', 20)
    type_ = request.args.get('type', 'server')
    try:
        page = int(page)
        page_size = int(page_size)
    except Exception:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
    if type_ not in ['server', 'client']:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')

    versions = Version.query.filter(Version.type == type_, Version.useable == true())
    count = versions.count()
    versions = versions.paginate(page=page, per_page=page_size)
    results = []
    for version in versions:
        results.append({
            'id': version.id,
            'version': version.version,
            'type': version.type.name,
            'description': version.description,
            'customer': version.customer,
            'is_latest': version.is_latest,
            'path': version.path
        })
    data = {'count': count, 'results': results}
    return success_response(data=data)


@version_manger.get('/versions/<int:version_id>/')
def version_retrieve(version_id):
    version = Version.query.filter(Version.id == int(version_id), Version.useable == true()).first()
    if not version:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '版本不存在或已弃用')
    data = {
        'id': version.id,
        'version': version.version,
        'type': version.type.name,
        'customer': version.customer,
        'description': version.description,
        'is_latest': version.is_latest,
        'path': version.path
    }
    return success_response(data=data)


@version_manger.get('/versions/last_version/')
def version_last():
    type_ = request.args.get('type', 'client')
    customer = request.args.get('customer')
    if type_ not in ['server', 'client'] or customer is None:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
    version = Version.query.filter(
        Version.type == type_,
        Version.useable == true(),
        Version.is_latest == true(),
        Version.customer == customer,
    ).first()
    if not version:
        return exception_response(ErrorCodes.NOT_FOUND, '未找到最新版')
    data = {
        'id': version.id,
        'version': version.version,
        'type': version.type.name,
        'description': version.description,
        'is_latest': version.is_latest,
        'path': version.path
    }
    return success_response(data=data)


# TODO 创建接口待修改
@version_manger.post('/versions/')
def version_create():
    type_ = request.json.get('type')
    customer = request.json.get('customer')
    if type_ not in ['server', 'client'] or customer is None:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
    version = request.json.get('version')
    version_obj = Version.query.filter(Version.type == type_, Version.version == version).first()
    if version_obj:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '版本已存在或弃用未显示')
    # dir_ = f'versions/{type_}/{version}'
    # if not os.path.exists(dir_):
    #     os.makedirs(dir_)
    # description = request.json.get('description')
    # version_obj = Version()
    # version_obj.type = type_
    # version_obj.version = version
    # version_obj.customer = customer
    # version_obj.path = path
    # version_obj.description = description
    # db.session.add(version_obj)
    # db.session.commit()
    # data = {
    #     'id': version_obj.id,
    #     'version': version_obj.version,
    #     'type': version_obj.type.name,
    #     'description': version_obj.description,
    #     'is_latest': version_obj.is_latest,
    #     'path': version_obj.path
    # }
    data = {}
    return success_response(data=data)


# 更新接口暂不开放， 仅开放更新最新版
# @version_manger.patch('/versions/<int:version_id>/')
# def version_patch(version_id):

#     type_ = request.json.get('type')
#     if type_ and type_ not in ['server', 'client']:
#         return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
#     version = request.json.get('version')
#     dir_ = request.json.get('dir')
#     version_obj = Version.query.filter(Version.id == int(version_id)).first()
#     if not version_obj:
#         return exception_response(ErrorCodes.INVALID_PARAMETERS, '版本不存在')
#     if type_:
#         version_obj.type = type_
#     if version:
#         version_obj.version = version
#     if dir_:
#         version_obj.dir_ = dir_
#     version_obj.save()
#     data = {
#         'id': version_obj.id,
#         'version': version_obj.version,
#         'type': version_obj.type,
#     }
#     return success_response(data=data)


@version_manger.patch('/versions/<int:version_id>/')
def version_patch_last(version_id):
    version_obj = Version.query.filter(Version.id == int(version_id)).first()
    if not version_obj:
        return exception_response(ErrorCodes.NOT_FOUND, '版本不存在')
    version_obj.is_latest = True
    type_ = version_obj.type
    customer = version_obj.customer
    Version.query.filter(
        Version.type == type_,
        Version.customer == customer,
        Version.id != int(version_id),
    ).update({'is_latest': False})
    db.session.commit()
    data = {
        'id': version_obj.id,
        'version': version_obj.version,
        'type': version_obj.type.name,
        'customer': version_obj.customer,
        'description': version_obj.description,
        'is_latest': version_obj.is_latest,
        'path': version_obj.path
    }
    return success_response(data=data)


@version_manger.delete('/versions/<int:version_id>/')
def version_delete(version_id):
    version_obj = Version.query.filter(Version.id == int(version_id), Version.useable == true()).first()
    if not version_obj:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '版本不存在或已弃用')
    version_obj.useable = False
    db.session.commit()
    return success_response()


@version_manger.get('/versions/manifest/')
def version_manifest():

    version = request.args.get('version')
    if not version:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
    type_ = request.args.get('type', 'server')
    if type_ not in ['server', 'client']:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '参数错误')
    version_obj = Version.query.filter(
        Version.version == version,
        Version.type == type_,
        Version.useable == true(),
    ).first()
    if not version_obj:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '版本不存在')
    dir_ = version_obj.dir
    manifest_file = f'{dir_.rstrip("/")}/manifest.json'
    if not os.path.exists(manifest_file):
        check_dir = f'{dir_.rstrip("/")}/{type_}'
        if type_ == 'client':
            check_dir = f'{dir_.rstrip("/")}/contents'
        manifest_data = check_project(check_dir)
        manifest_data['version'] = version
        with open(manifest_file, 'w', encoding='utf-8') as w:
            w.write(json.dumps(manifest_data, ensure_ascii=False))
        return success_response(data=manifest_data)
    manifest_data = None
    with open(manifest_file, 'r', encoding='utf-8') as fin:
        manifest_data = fin.read()
    if manifest_data is None:
        return exception_response(ErrorCodes.INVALID_PARAMETERS, '对比文件错误')
    return success_response(data=json.loads(manifest_data))
